import { SelectionModel, ContentModel, ModelEvent } from "../models"
import { BaseOpt } from "../operations"
import { InputEventer, SelectionEventer } from '../event'
import Render from "../renders"
import { BaseEvent } from "../event/base"

export class Editor {

  private _contentModel = new ContentModel()
  private _selectionModel = new SelectionModel()

  private element!: HTMLElement

  private render!: Render

  constructor(element: HTMLElement) {
    console.log("!初始化!")
    this.element = element
    this.render = new Render(element)

    this.registeEventer(new InputEventer())
    this.registeEventer(new SelectionEventer())

    this._contentModel.on(ModelEvent.CONTENT_UPDATE, this._onContentUpdate.bind(this))
    this._selectionModel.on(ModelEvent.SELECTION_CHANGE, this._onSelectionUpdate.bind(this))
  }
  registeEventer(eventer:BaseEvent){
    eventer.init(this.element, this).addEventListen()
  }
  unregistEventer(eventer:BaseEvent){
    eventer.removeEventListen()
  }
  /**
   * 提交操作
   * @param opt 
   */
  commit(opt:BaseOpt){
    opt.attach(this._contentModel,this._selectionModel)
    opt.apply()
  }
  /**
   * 请求资源
   * @param action 
   */
  require(action:ActionFuncion){
    action && action(this._selectionModel,this._contentModel)
  }
  
  updateSelection(index:number,length:number){
    this._selectionModel.sync(index, length)
  }
  storeSelection(){
    this._selectionModel.push()
  }
  restoreSelection(){
    this._selectionModel.pop()
  }

  private _onContentUpdate() {
    this.render.renderContent(this._contentModel)
  }
  private _onSelectionUpdate() {
    this.render.renderSelection(this._selectionModel)
  }
}

type ActionFuncion = (selection:SelectionModel,content:ContentModel)=>void
